package com.hmdp.utils;


import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author zcf
 */
public class SimpleRedisLock implements ILock {
    private String name;
    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //添加一个key前缀
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    //初始化lua脚本
   private static  final DefaultRedisScript<Long> UNLOCK_SCRIPT;
   static {
       UNLOCK_SCRIPT=new DefaultRedisScript<>();
       UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
       UNLOCK_SCRIPT.setResultType(Long.class);
   }
    @Override
    public boolean tryLock(long timeOutSec) {
        //1.获取当前线程id
        long threadId = Thread.currentThread().getId();
        //利用setNx方法尝试获取锁
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId + "", timeOutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(aBoolean);
    }

    @Override
    public void unlock() {
        /*//解决误删问题版本1
        //1.获取当前线程标识，也就是线程id
        String threadId = ID_PREFIX + Thread.currentThread().getId() + "-";
        //2.获取redis中的线程标识
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (threadId.equals(id)) {
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }*/

        //使用lua脚本解决原子性问题
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX+name),
                ID_PREFIX+Thread.currentThread().getId()
        );
    }
}
